package fsnotify

import (
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

// Watch a given recursive file path
func (w *Watcher) RecursiveWatch(path string) error {
	fi, err := os.Stat(path)
	if err != nil {
		return err
	}

	if !fi.IsDir() {
		return w.WatchFlags(path, FSN_ALL)
	}

	paths, err := w.subFolders(path)
	if err != nil {
		return err
	}

	for _, v := range paths {
		if err := w.WatchFlags(v, FSN_ALL); err != nil {
			return err
		}
	}
	return nil
}

func (w *Watcher) subFolders(path string) ([]string, error) {
	var paths []string

	_ = filepath.Walk(path, func(newPath string, info fs.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			name := info.Name()

			// skip folders that begin with a dot
			if shouldIgnoreFile(name) && name != "." && name != ".." {
				return filepath.SkipDir
			}

			paths = append(paths, newPath)
		}
		return nil
	})

	return paths, nil
}

// Remove a given recursive file path
func (w *Watcher) RecursiveRemove(path string) error {
	fi, err := os.Stat(path)
	if err != nil {
		return err
	}

	if !fi.IsDir() {
		return w.RemoveWatch(path)
	}

	paths, err := w.subFolders(path)
	if err != nil {
		return err
	}

	for _, v := range paths {
		_ = w.RemoveWatch(v)
		//if err := w.RemoveWatch(v); err != nil {
		//	return err
		//}
	}
	return nil
}

// shouldIgnoreFile determines if a file should be ignored.
// File names that begin with "." or "_" are ignored by the go tool.
func shouldIgnoreFile(name string) bool {
	return strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_")
}
